package com.app.util.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** 
 * 说明：常用工具
 */
public class Tools {
	
	/**
	 * 随机生成六位数验证码 
	 * @return
	 */
	public static int getRandomNum(){
		 Random r = new Random();
		 return r.nextInt(900000)+100000;//(Math.random()*(999999-100000)+100000)
	}
	
	/**
	 * 检测字符串是否不为空(null,"","null")
	 * @param s
	 * @return 不为空则返回true，否则返回false
	 */
	public static boolean notEmpty(String s){
		return s!=null && !"".equals(s) && !"null".equals(s);
	}
	
	/**
	 * 检测字符串是否为空(null,"","null")
	 * @param s
	 * @return 为空则返回true，不否则返回false
	 */
	public static boolean isEmpty(String s){
		return s==null || "".equals(s) || "null".equals(s);
	}
	
	/**
	 * 字符串转换为字符串数组
	 * @param str 字符串
	 * @param splitRegex 分隔符
	 * @return
	 */
	public static String[] str2StrArray(String str,String splitRegex){
		if(isEmpty(str)){
			return null;
		}
		return str.split(splitRegex);
	}
	
	/**
	 * 用默认的分隔符(,)将字符串转换为字符串数组
	 * @param str	字符串
	 * @return
	 */
	public static String[] str2StrArray(String str){
		return str2StrArray(str,",\\s*");
	}
	
	/**
	 * 按照yyyy-MM-dd HH:mm:ss的格式，日期转字符串
	 * @param date
	 * @return yyyy-MM-dd HH:mm:ss
	 */
	public static String date2Str(Date date){
		return date2Str(date,"yyyy-MM-dd HH:mm:ss");
	}
	
	/**
	 * 按照yyyy-MM-dd HH:mm:ss的格式，字符串转日期
	 * @param date
	 * @return
	 */
	public static Date str2Date(String date){
		if(notEmpty(date)){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				return sdf.parse(date);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return new Date();
		}else{
			return null;
		}
	}
	
	/**
	 * 按照参数format的格式，日期转字符串
	 * @param date
	 * @param format
	 * @return
	 */
	public static String date2Str(Date date,String format){
		if(date!=null){
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			return sdf.format(date);
		}else{
			return "";
		}
	}
	
	/**
	 * 把时间根据时、分、秒转换为时间段
	 * @param StrDate
	 */
	public static String getTimes(String StrDate){
		String resultTimes = "";
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    java.util.Date now;
	    
	    try {
	    	now = new Date();
	    	java.util.Date date=df.parse(StrDate);
	    	long times = now.getTime()-date.getTime();
	    	long day  =  times/(24*60*60*1000);
	    	long hour = (times/(60*60*1000)-day*24);
	    	long min  = ((times/(60*1000))-day*24*60-hour*60);
	    	long sec  = (times/1000-day*24*60*60-hour*60*60-min*60);
	        
	    	StringBuffer sb = new StringBuffer();
	    	//sb.append("发表于：");
	    	if(hour>0 ){
	    		sb.append(hour+"小时前");
	    	} else if(min>0){
	    		sb.append(min+"分钟前");
	    	} else{
	    		sb.append(sec+"秒前");
	    	}
	    		
	    	resultTimes = sb.toString();
	    } catch (ParseException e) {
	    	e.printStackTrace();
	    }
	    
	    return resultTimes;
	}
	
	/**
	 * 写txt里的单行内容
	 * @param filePath  文件路径
	 * @param content  写入的内容
	 */
	public static void writeFile(String fileP,String content){
		String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../";	//项目路径
		filePath = (filePath.trim() + fileP.trim()).substring(6).trim();
		if(filePath.indexOf(":") != 1){
			filePath = File.separator + filePath;
		}
		try {
	        OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(filePath),"utf-8");      
	        BufferedWriter writer=new BufferedWriter(write);          
	        writer.write(content);      
	        writer.close(); 

	        
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	  * 验证邮箱
	  * @param email
	  * @return
	  */
	 public static boolean checkEmail(String email){
	  boolean flag = false;
	  try{
	    String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
	    Pattern regex = Pattern.compile(check);
	    Matcher matcher = regex.matcher(email);
	    flag = matcher.matches();
	   }catch(Exception e){
	    flag = false;
	   }
	  return flag;
	 }
	
	 /**
	  * 验证手机号码
	  * @param mobiles
	  * @return
	  */
	 public static boolean checkMobileNumber(String mobileNumber){
	  boolean flag = false;
	  try{
	    Pattern regex = Pattern.compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$");
	    Matcher matcher = regex.matcher(mobileNumber);
	    flag = matcher.matches();
	   }catch(Exception e){
	    flag = false;
	   }
	  return flag;
	 }
	 
	/**
	 * 检测KEY是否正确
	 * @param paraname  传入参数
	 * @param FKEY		接收的 KEY
	 * @return 为空则返回true，不否则返回false
	 */
	public static boolean checkKey(String paraname, String FKEY){
		paraname = (null == paraname)? "":paraname;
		return MD5.md5(paraname+DateUtil.getDays()+",fh,").equals(FKEY);
	}
	 
	/**
	 * 读取txt里的单行内容
	 * @param filePath  文件路径
	 */
	public static String readTxtFile(String fileP) {
		try {
			
			String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../";	//项目路径
			filePath = filePath.replaceAll("file:/", "");
			filePath = filePath.replaceAll("%20", " ");
			filePath = filePath.trim() + fileP.trim();
			if(filePath.indexOf(":") != 1){
				filePath = File.separator + filePath;
			}
			String encoding = "utf-8";
			File file = new File(filePath);
			if (file.isFile() && file.exists()) { 		// 判断文件是否存在
				InputStreamReader read = new InputStreamReader(
				new FileInputStream(file), encoding);	// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					return lineTxt;
				}
				read.close();
			}else{
				System.out.println("找不到指定的文件,查看此路径是否正确:"+filePath);
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
		}
		return "";
	}
	//数字替换成中文 
    public static String convertToChineseNumber(int number) {
    	String chineseNumber = "";
       	String[] num = { "O", "一", "二", "三", "四", "五", "六", "七", "八", "九" };  
        String tempNumber = String.valueOf(number);
        int tempNumberLength = tempNumber.length();
       	if (!"0".equals(number)) {
        	 String[] arr = tempNumber.split("");
        	 for (int i=1;i<arr.length;i++){
        	 	switch (Integer.parseInt(arr[i])){
        	 		case 0: {
        	 			chineseNumber += num[0];
        	 			break;
       	 			}
        	 		case 1: {
    	    	 		chineseNumber += num[1];
    	    	 		if (arr.length==3 && i == 1)
    	    	 			chineseNumber += "十";	
    	    	 		break;
        	 		}
        	 		case 2: {
    	    	 		chineseNumber += num[2];
    	    	 		if (arr.length==3 && i == 1)
    	    	 			chineseNumber += "十";	
    	    	 		break;
        	 		}
        	 		case 3: {
    	    	 		chineseNumber += num[3];
    	    	 		if (arr.length==3 && i == 1)
    	    	 			chineseNumber += "十";	
    	    	 		break;
        	 		}
        	 		case 4: {
    	    	 		chineseNumber += num[4];
    	    	 		if (arr.length==3 && i == 1)
    	    	 			chineseNumber += "十";	
    	    	 		break;
        	 		}
        	 		case 5: {
    	    	 		chineseNumber += num[5];
    	    	 		if (arr.length==3 && i == 1)
    	    	 			chineseNumber += "十";	
    	    	 		break;
        	 		}
        	 		case 6: {
    	    	 		chineseNumber += num[6];
    	    	 		if (arr.length==3 && i == 1)
    	    	 			chineseNumber += "十";	
    	    	 		break;
        	 		}
        	 		case 7: {
    	    	 		chineseNumber += num[7];
    	    	 		if (arr.length==3 && i == 1)
    	    	 			chineseNumber += "十";	
    	    	 		break;
        	 		}
        	 		case 8: {
    	    	 		chineseNumber += num[8];
    	    	 		if (arr.length==3 && i == 1)
    	    	 			chineseNumber += "十";	
    	    	 		break;
        	 		}
        	 		case 9: {
    	    	 		chineseNumber += num[9];
    	    	 		if (arr.length==3 && i == 1)
    	    	 			chineseNumber += "十";	
    	    	 		break;
        	 		}
        	 		default:break;
        	 	}
        	 }		 
        }
    	return chineseNumber;
    }
  //数字替换成中文 
    public static String convertToChineseDate(int number) {
    	String chineseNumber = "";
        switch (number){
	 		case 0: {
	 			chineseNumber = "O";
	 			break;
 			}
	 		case 1: {
	 			chineseNumber = "一";
    	 		break;
	 		}
	 		case 2: {
	 			chineseNumber = "二";
    	 		break;
	 		}	 		
	 		case 3: {
	 			chineseNumber = "三";
    	 		break;
	 		}	 		
	 		case 4: {
	 			chineseNumber = "四";
    	 		break;
	 		}	 		
	 		case 5: {
	 			chineseNumber = "五";
    	 		break;
	 		}	 		
	 		case 6: {
	 			chineseNumber = "六";
    	 		break;
	 		}	 		
	 		case 7: {
	 			chineseNumber = "七";
    	 		break;
	 		}	 		
	 		case 8: {
	 			chineseNumber = "八";
    	 		break;
	 		}	 		
	 		case 9: {
	 			chineseNumber = "九";
    	 		break;
	 		}	 		
	 		case 10: {
	 			chineseNumber = "十";
    	 		break;
	 		}
	 		case 11: {
	 			chineseNumber = "十一";
    	 		break;
	 		}
	 		case 12: {
	 			chineseNumber = "十二";
    	 		break;
	 		}	 		
	 		case 13: {
	 			chineseNumber = "十三";
    	 		break;
	 		}	 		
	 		case 14: {
	 			chineseNumber = "十四";
    	 		break;
	 		}	 		
	 		case 15: {
	 			chineseNumber = "十五";
    	 		break;
	 		}	 		
	 		case 16: {
	 			chineseNumber = "十六";
    	 		break;
	 		}	 		
	 		case 17: {
	 			chineseNumber = "十七";
    	 		break;
	 		}	 		
	 		case 18: {
	 			chineseNumber = "十八";
    	 		break;
	 		}	 		
	 		case 19: {
	 			chineseNumber = "十九";
    	 		break;
	 		}	 		
	 		case 20: {
	 			chineseNumber = "二十";
    	 		break;
	 		}
	 		case 21: {
	 			chineseNumber = "二十一";
    	 		break;
	 		}
	 		case 22: {
	 			chineseNumber = "二十二";
    	 		break;
	 		}	 		
	 		case 23: {
	 			chineseNumber = "二十三";
    	 		break;
	 		}	 		
	 		case 24: {
	 			chineseNumber = "二十四";
    	 		break;
	 		}	 		
	 		case 25: {
	 			chineseNumber = "二十五";
    	 		break;
	 		}	 		
	 		case 26: {
	 			chineseNumber = "二十六";
    	 		break;
	 		}	 		
	 		case 27: {
	 			chineseNumber = "二十七";
    	 		break;
	 		}	 		
	 		case 28: {
	 			chineseNumber = "二十八";
    	 		break;
	 		}	 		
	 		case 29: {
	 			chineseNumber = "二十九";
    	 		break;
	 		}	 		
	 		case 30: {
	 			chineseNumber = "三十";
    	 		break;
	 		}
	 		case 31: {
	 			chineseNumber = "三十一";
    	 		break;
	 		}
	 		default:break;
        }
    	return chineseNumber;
    }
    
    public static String removeNull(String tmpStr) {
        if (tmpStr == null || tmpStr.equals("null"))
            return "";
        else
            return tmpStr;
    }
    
    public static String removeNull(Integer tmpStr) {
        if (tmpStr == null || tmpStr.equals("null")||tmpStr==0)
            return "";
        else
            return String.valueOf(tmpStr);
    }
  //取名称
    public static String subName(String tmpStr) {
	    if (tmpStr == null || tmpStr.equals("null"))
	        return "";
	    else if (tmpStr.lastIndexOf("/") >=0)
	        return tmpStr.substring(tmpStr.lastIndexOf("/") + 1);
	    else
	        return tmpStr;
	}
	
  //取文件扩展名
    public static String file_etc(String tmpStr) {
        if (tmpStr == null || tmpStr.equals("null"))
            return "";
        else if (tmpStr.indexOf(".") > 0)
            return tmpStr.substring(tmpStr.lastIndexOf("."));
        else
            return tmpStr;
    }
    
    public static String subMoreName(String tmpStr) {
        String tName = "";
        if (tmpStr == null || tmpStr.equals("null"))
            return "";
        String[] tmpArry = tmpStr.split(",");
        for (int i = 0; i < tmpArry.length; i++) {
            if (i == 0)
                tName = tmpArry[i].substring(tmpArry[i].lastIndexOf("/") + 1);
            else
                tName=tName+","+tmpArry[i].substring(tmpArry[i].lastIndexOf("/") + 1);
        }
            return tName;
    }
    //取id
    public static String subID(String tmpStr) {
      if (tmpStr == null || tmpStr.equals("null"))
          return "";
      else if (tmpStr.lastIndexOf("/") > 0)
          return tmpStr.substring(2, tmpStr.lastIndexOf("/"));
      else
          return tmpStr;
    }
    //转换大小
    public static String ConvertSizeToStr(long l) {
		java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");
		if (l < 1024L)
			return l + "bytes";
		else if (l / 1024F < 1024F)
			return df.format(l / 1024F) + "K";

		else if (l / 1024F / 1024 < 1024F)
			return df.format(l / 1024F / 1024) + "M";
		else
			// if (l / 1024F / 1024 / 1024 < 1024F)
			return df.format(l / 1024F / 1024 / 1024) + "G";

	}
    
    public static String getTianQi(String cityCode) throws IOException{
		try {
		URL url = new URL("http://weather.news."+(char)113+(char)113+".com/inc/07_ss"+cityCode+".htm");
		URLConnection conn = url.openConnection();
		InputStream in = conn.getInputStream();
		int i = in.read();
		StringBuffer bf = new StringBuffer();
	 	while(i!=-1) {
			bf.append((char)i);
			i=in.read();
		}
	 	String s = new String(bf.toString().getBytes("ISO8859-1"),"utf-8");
	 	int j = s.indexOf("wht1 lk37"); 
	 	String ss = s.substring(j); 
	 	String str = ss.substring(ss.indexOf(">")+1,ss.indexOf("<"));
		String city = str.trim();
		j = s.indexOf("wht2 lk37")+16; 
		ss = s.substring(j); 
		str = ss.substring(ss.indexOf(">")+1,ss.indexOf("<"));
		String weather = str.trim();
		String tu="";
		if("晴".equals(weather)){
			tu="sun";
		}else if("晴转多云".equals(weather)){
			tu="suntocloud";
		}else if("晴转小雨".equals(weather)){
			tu="suntorain";
		}else if("阴".equals(weather)){
			tu="yin";
		}else if("阴转多云".equals(weather)){
			tu="yintocloud";
		}else if("阴转晴".equals(weather)){
			tu="yintosun";
		}else if("小雨".equals(weather)){
			tu="smallrain";
		}else if("小雨转大雨".equals(weather)){
			tu="raintobig";
		}else if("小雨转中雨".equals(weather)){
			tu="smalltomindd";
		}else if("小雨转雷雨".equals(weather)){
			tu="raintomine";
		}else if("大雨".equals(weather)){
			tu="bigrain";
		}else if("阵雨".equals(weather)){
			tu="somerain";
		}else if("大雨转小雨".equals(weather)){
			tu="bigraintosmall";
		}else if("大雨转阵雨".equals(weather)){
			tu="bigraintomindd";
		}else if("大雨雷雨".equals(weather)){
			tu="bigraintomine";
		}else if("小雪".equals(weather)){
			tu="smallsnow";
		}else if("小雪转大雪".equals(weather)){
			tu="bigsnow";
		}else if("大雪".equals(weather)){
			tu="bigsnow";
		}else if("大雪转小雪".equals(weather)){
			tu="bigsnow";
		}else{
			tu="cloud";
		}
		j = s.indexOf("/div"); 
		ss = s.substring(j); 
		str = ss.substring(ss.indexOf(">")+1,ss.indexOf("<"));
		String temp = str.trim();
		j = s.indexOf("whp3 lk37"); 
		ss = s.substring(j); 
		str = ss.substring(ss.indexOf(">")+1,ss.indexOf("<"));
		String wind = str.trim();
		j = s.indexOf("br"); 
		ss = s.substring(j); 
		str = ss.substring(ss.indexOf(">")+1,ss.indexOf("<"));
		String ray = str.trim();
		j = s.lastIndexOf("br"); 
		ss = s.substring(j); 
		str = ss.substring(ss.indexOf(">")+1,ss.indexOf("<"));
		String air = str.trim();
		return city+","+weather+","+temp+","+tu;
		}catch(Exception ex){
			//ex.printStackTrace();
			return " , , , ";
		}
	}
  //构造路径
    public static void initPath(String path) {
        java.io.File file_dir = new java.io.File( String.valueOf(path));
        if (!file_dir.exists())
            file_dir.mkdirs();
    }
    
    public static byte[] getBytes(FileInputStream fs){  
	    if (fs == null){  
	        return null;  
	    }  
	    try{  
	        ByteArrayOutputStream out = new ByteArrayOutputStream(1000);  
	        byte[] b = new byte[1000];  
	        int n;  
	        while ((n = fs.read(b)) != -1)  
	            out.write(b, 0, n);  
	        fs.close();  
	            out.close();  
	        return out.toByteArray();  
	    } catch (Exception e){  
	        e.printStackTrace();  
	    }  
	    return null;  
	}
    
  //过滤所有html
    public static String toTxt(String s) {
        if (s == null) {
            return null;
        } else {
        	s=s.replaceAll("<P>","");
        	s=s.replaceAll("<p>","");
        	s=s.replaceAll("<BR>","");
        	s=s.replaceAll("<br>","");
        	s=s.replaceAll("</P>","");
        	s=s.replaceAll("</p>","");
        	s=s.replaceAll("<[.[^<]]*>","");
        	s=s.replaceAll("《P》","");
            s=s.replaceAll("\n", "");
            s=s.replaceAll("\t", "");
            s=s.replaceAll(" ", "");
            s=s.replaceAll("\r\n", "");
            s=s.replaceAll("&nbsp;", " ");
            return s;
            
        }
    }
    
	public static void main(String[] args) {
		System.out.println(getRandomNum());
	}
	
}
